﻿using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// Tween the widget's size.
/// </summary>

[RequireComponent(typeof(RectTransform))]
[AddComponentMenu("UGUI/Tween/Tween Height")]
public class UGUITweenHeight : UGUITweener
{
    public override object fromValue { get { return from; } set { from = (int)value; } }
    public override object toValue { get { return to; } set { to = (int)value; } }

    public int from = 100;
	public int to = 100;
	public bool updateTable = false;

    RectTransform mWidget;

	public RectTransform cachedWidget { get { if (mWidget == null) mWidget = GetComponent<RectTransform>(); return mWidget; } }

    /// <summary>
    /// Tween's current value.
    /// </summary>
    public int value
    {
        get
        {
            return (int)cachedWidget.sizeDelta.y;
        }
        set
        {
            var sizeDelta = cachedWidget.sizeDelta;
            sizeDelta.y = value;

            cachedWidget.sizeDelta = sizeDelta;
        }
    }

	/// <summary>
	/// Tween the value.
	/// </summary>
	protected override void OnUpdate (float factor, bool isFinished)
	{
		value = Mathf.RoundToInt(from * (1f - factor) + to * factor);
	}

	/// <summary>
	/// Start the tweening operation.
	/// </summary>
	static public UGUITweenHeight Begin (RectTransform widget, float duration, int height)
	{
        UGUITweenHeight comp = UGUITweener.Begin<UGUITweenHeight>(widget.gameObject, duration);
		comp.from = (int)widget.sizeDelta.y;
		comp.to = height;

		if (duration <= 0f)
		{
			comp.Sample(1f, true);
			comp.enabled = false;
		}
		return comp;
	}

	[ContextMenu("Set 'From' to current value")]
	public override void SetStartToCurrentValue () { from = value; }

	[ContextMenu("Set 'To' to current value")]
	public override void SetEndToCurrentValue () { to = value; }

	[ContextMenu("Assume value of 'From'")]
	void SetCurrentValueToStart () { value = from; }

	[ContextMenu("Assume value of 'To'")]
	void SetCurrentValueToEnd () { value = to; }
}
